package com.cskaoyan.market.controller.wx;

import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.service.wx.WxAuthService;
import com.cskaoyan.market.shiro.MarketToken;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("wx/auth")
public class WxAuthController {

    @Autowired
    private WxAuthService wxAuthService;

    @Autowired
    SecurityManager securityManager;


    @PostMapping("login")
    public Object login(@RequestBody Map params){
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        String username = (String) params.get("username");
        String password = (String) params.get("password");
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            // todo
            return ResponseUtil.badArgument();
        }
        //TODO
        MarketToken token = new MarketToken(username, password, "wx");
        try {
            subject.login(token);
        }catch (Exception e){
            return ResponseUtil.fail(404, "用户名或者密码错误");
        }

        MarketUser user = (MarketUser) subject.getPrincipal();
        Session session = subject.getSession();
        session.setAttribute("user", user);
        Map<String, String> userInfo = new HashMap<>();
        userInfo.put("nickName", user.getNickname());
        userInfo.put("avatarUrl", user.getAvatar());
        Map<String, Object> data = new HashMap<>();
        data.put("userInfo", userInfo);
        //todo
        data.put("token", session.getId());
        Object ok = ResponseUtil.ok(data);
        return ok;
    }

    //但是shiro的会话管理情况下也是依赖于cookie的，如果在小程序里面也是无法使用的
    //但是shiro相较于HttpSession的会话管理技术的优势在于支持自定义，也就是不仅仅只可以从Cookie请求头中获取，还可以支持从其他请求头中进行获取
}
